package com.sso.action.sys;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONArray;
import com.sso.common.enums.SysRoleEnum;
import com.sso.entity.SysMenuRole;
import com.sso.exception.SelectException;
import com.sso.manager.SysMenuManager;
import com.sso.manager.SysMenuRoleManager;
import com.sso.manager.SysUserRoleManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import com.alibaba.fastjson.JSONObject;
import com.tools.util.JSONUtils;
import com.tools.util.RequestUtils;
import com.tools.util.StrUtils;
import com.sso.action.BaseAction;
import com.sso.common.ConstantDate;
import com.sso.common.enums.FlagStatus;
import com.sso.entity.Page;
import com.sso.entity.SysRole;
import com.sso.entity.vo.SysRoleVo;
import com.sso.manager.SysRoleManager;

/**
 * 角色action
 * @author Admin
 *
 */
@Controller
@RequestMapping("/role")
public class SysRoleAction extends BaseAction{
	private Logger logger =LoggerFactory.getLogger(this.getClass());
	@Autowired
	private SysRoleManager manager;
	@Autowired
	private SysMenuManager menuManager;
	@Autowired
	private SysUserRoleManager userRoleManager;
	@Autowired
	private SysMenuRoleManager menuRoleManager;

	/**
	 * 角色管理页面
	 * @return
	 */
	@RequestMapping("gotoRoleView")
	public ModelAndView sysRoleView(HttpServletRequest request){
		ModelAndView view = new ModelAndView("/manager/sysRoleManager");
		Map<String,Object> filterMap = WebUtils.getParametersStartingWith(request, "");
		filterMap.put("notStatus", ConstantDate.RoleStatus.DEL.key);
		Page<SysRoleVo> page = manager.selectByPage(filterMap);
		view.addObject("page",page);
		return view;
	}


	/**
	 * 删除角色
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("deleteRole")
	public void deleteRole(HttpServletRequest request,HttpServletResponse response){
		String status = FlagStatus.ERROR.value;
		Map<String,Object> filterMap = RequestUtils.getParametersToMap(request,"");
		String id = (String)filterMap.get("id");
		if(StrUtils.isEmpty(id)){
			this.outputJson(status, "要删除的角色不存在", response);
			return;
		}
			SysRole role = manager.selectById(id);
			if(StrUtils.isEmpty(role.getId())){
				this.outputJson(status, "要删除的角色不存在", response);
				return;
			}
		try {
			manager.deleteById(role.getId());
			this.outputJson(FlagStatus.SUCCESS.value, "删除成功", response);
		} catch (Exception e) {
			e.printStackTrace();
			this.outputJson(FlagStatus.ERROR.value,"删除失败，请联系管理人员!",response);
		}
	}
	/**
	 * 启用角色
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("startRole")
	public void startRole(HttpServletRequest request,HttpServletResponse response){
		String status = FlagStatus.ERROR.value;
		Map<String,Object> filterMap = RequestUtils.getParametersToMap(request,"");
		String id = (String)filterMap.get("id");
		if(StrUtils.isEmpty(id)){
			this.outputJson(status, "要启用的角色不存在", response);
			return;
		}
		try {
			SysRole role = manager.selectById(id);
			if(StrUtils.isEmpty(role.getId())){
				this.outputJson(status, "要删除的角色数据不存在", response);
				return;
			}
			role.setStatus(ConstantDate.RoleStatus.DEL.key);
			manager.save(role);
			this.outputJson(FlagStatus.SUCCESS.value, "删除成功", response);
		} catch (Exception e) {
			e.printStackTrace();
			this.outputJson(status,"操作失败，请联系管理人员",response);
		}
	}
	/**
	 * 停用角色
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("stopRole")
	public void stopRole(HttpServletRequest request,HttpServletResponse response){
		String status = FlagStatus.ERROR.value;
		Map<String,Object> filterMap = RequestUtils.getParametersToMap(request,"");
		String id = (String)filterMap.get("id");
		if(StrUtils.isEmpty(id)){
			this.outputJson(status, "请选择要停用的角色", response);
			return;
		}
		try {
			SysRole role = manager.selectById(id);
			if(StrUtils.isEmpty(role.getId())){
				this.outputJson(status, "要停用的角色不存在", response);
				return;
			}
			role.setStatus(SysRoleEnum.status.STOP.key);
			manager.save(role);
			this.outputJson(FlagStatus.SUCCESS.value, "停用成功", response);
		} catch (Exception e) {
			e.printStackTrace();
			this.outputJson(status,"操作失败，请联系管理人员",response);
		}
	}
	
	/**
	 * 根据ID查询单个角色信息
	 * @param request
	 * @param response
	 */
	@RequestMapping("selectRoleById")
	public void selectRoleById(HttpServletRequest request,HttpServletResponse response){
		String id = (String)RequestUtils.getParametersToMap(request, "").get("id");
		String status = FlagStatus.ERROR.value;
		if(StrUtils.isEmpty(id)){
			this.outputJson(status, "请选择要查询的角色", response);
			return;
		}
		SysRole role = manager.selectById(id);
		if(StrUtils.isEmpty(role.getId())){
			this.outputJson(status, "要查询的角色不存在", response);
		}
		String filterAttr = "id,roleName,remark,parentRoleId";
		String jsonStr = JSONUtils.toJsonInAttrbuite(role, filterAttr);
		JSONObject json = new JSONObject();
		json.put("status", FlagStatus.SUCCESS.value);
		json.put("info", JSONObject.parse(jsonStr));
		this.outputJson(json, response);
	}
	
	/**
	 * 更新角色
	 * @param request
	 * @param response
	 * @throws Exception 
	 */
	@RequestMapping("saveRole")
	public void updateRole(SysRole role,HttpServletResponse response){
		String status = FlagStatus.ERROR.value;
		try {
			if(role==null){
				this.outputJson(status, "要保存的角色信息异常", response);
				return;
			}
			if(StrUtils.isEmpty(role.getRoleName())){
				this.outputJson(status, "请输入角色名称", response);
				return;
			}
			manager.save(role);
			this.outputJson("T", "保存成功", response);
		} catch (Exception e) {
			e.printStackTrace();
			this.outputJson("F", "保存失败", response);
		}
	}
	
	@RequestMapping("getRoleList")
	public void getRoleList(HttpServletResponse response){
		Map<String,Object> filterMap = new HashMap<String, Object>();
		filterMap.put("notStatus", ConstantDate.RoleStatus.DEL.key);
		try {
		List<SysRoleVo> roleList = manager.selectVoByProperty(filterMap);
		//要转换JSON的属性
		String attr = "id,roleName,parentRoleId";
		String arr = JSONUtils.toJsonInAttrbuite(roleList, attr);
		this.outputJsonString(arr, response);
		} catch (SelectException e) {
			e.printStackTrace();
			this.outputJsonString("",response);
		}
	}

	/**
	 * 保存角色所拥有的菜单权限
	 * @param request
	 * @param response
     */
    @RequestMapping("saveRoleAuth")
	public void saveRoleAuth(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> param = RequestUtils.getParametersToMap(request, "");
		String flag = FlagStatus.ERROR.value;
		String roleid =(String)param.get("roleid");
		String[] menus = (String[])param.get("menuArray[]");
			//参数校验
			if(StrUtils.isEmpty(roleid)){
				this.outputJson(flag,"请选择要授权的角色", response);
				return;
			}
		try {
			SysRole role = manager.selectById(roleid);
			if(StrUtils.isEmpty(role.getId())){
				this.outputJson(flag,"要授权的角色不存在",response);
				return;
			}
			if(menus==null || menus.length==0){
				this.outputJson(flag, "请选择角色所拥有的菜单", response);
				return;
			}
            manager.saveRoleAuth(roleid,menus);
			this.outputJson(FlagStatus.SUCCESS.value, "授权成功", response);
		} catch (Exception e) {
			e.printStackTrace();
			this.outputJson(FlagStatus.ERROR.value,"操作失败，请联系管理人员",response);
		}
	}

	/**
	 * 查询角色权限信息
	 * @param roleId 角色ID
	 * @param request
	 * @param response
     */
	@RequestMapping("selectRoleAuth")
	public void selectRoleAuth(HttpServletRequest request,HttpServletResponse response){
		String roleId = RequestUtils.getParameters(request,"roleId");
		String flag = FlagStatus.ERROR.value;
		if(StrUtils.isEmpty(roleId)){
			this.outputJson(flag,"请选择要查询的角色",response);
			return;
		}
		List<SysMenuRole> menuRoleList = menuRoleManager.selectByRoleId(roleId);
		Object arr = JSONArray.toJSON(menuRoleList);
		this.outputJson(FlagStatus.SUCCESS.value,arr,response);
	}
}
